package logger

import (
	"fmt"
	"log"
	"os"
	"runtime"
	"strconv"
)

const (
	PanicLevel int = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
)

type LogFile struct {
	level    int
	logTime  int64
	fileName string
	fileFd   *os.File
}

var logFile LogFile

func Config(logFolder string, level int) {
	logFile.fileName = logFolder
	logFile.level = level
}

func SetLevel(level int) {
	logFile.level = level
}

func Debugf(format string, args ...interface{}) {
	if logFile.level >= DebugLevel {
		funcName, line := getFuncNameAndLine(3)
		log.SetPrefix("debug "+funcName+" "+line+" ")
		log.Output(2, fmt.Sprintf(format, args...))
	}
}

func Infof(format string, args ...interface{}) {
	if logFile.level >= InfoLevel {
		funcName, line := getFuncNameAndLine(3)
		log.SetPrefix("info "+funcName+" "+line+" ")
		log.Output(2, fmt.Sprintf(format, args...))
	}
}

func Warnf(format string, args ...interface{}) {
	if logFile.level >= WarnLevel {
		funcName, line := getFuncNameAndLine(3)
		log.SetPrefix("warn "+funcName+" "+line+" ")
		log.Output(2, fmt.Sprintf(format, args...))
	}
}

func Errorf(format string, args ...interface{}) {
	if logFile.level >= ErrorLevel {
		funcName, line := getFuncNameAndLine(3)
		log.SetPrefix("error "+funcName+" "+line+" ")
		log.Output(2, fmt.Sprintf(format, args...))
	}
}

func Fatalf(format string, args ...interface{}) {
	if logFile.level >= FatalLevel {
		log.SetPrefix("fatal ")
		log.Output(2, fmt.Sprintf(format, args...))
	}
}

func getFuncNameAndLine(skip int)  (string,string){
	pc, _, line, _ := runtime.Caller(skip)
	function := runtime.FuncForPC(pc)
	return function.Name(),strconv.Itoa(line)
}





